import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
// import { TypeOrmModule } from '@nestjs/typeorm';
import { ThrottlerModule } from '@nestjs/throttler';
import { CacheModule } from '@nestjs/cache-manager';
import { ScheduleModule } from '@nestjs/schedule';
import { EventEmitterModule } from '@nestjs/event-emitter';
import { ServeStaticModule } from '@nestjs/serve-static';
import { join } from 'path';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { DatabaseModule } from './database/database.module';
import { RedisModule } from './redis/redis.module';
import { RoomsModule } from './rooms/rooms.module';
import { WebsocketModule } from './websocket/websocket.module';
import { HealthModule } from './health/health.module';
import { configValidationSchema } from './config/config.validation';
import { databaseConfig } from './config/database.config';
import { redisConfig } from './config/redis.config';
import { appConfig } from './config/app.config';

@Module({
  imports: [
    // 配置模块
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: ['.env.local', '.env'],
      validationSchema: configValidationSchema,
      load: [appConfig, databaseConfig, redisConfig],
      cache: true,
      expandVariables: true,
    }),

    // 限流模块
    ThrottlerModule.forRootAsync({
      useFactory: () => ({
        throttlers: [
          {
            name: 'short',
            ttl: 1000, // 1秒
            limit: 10, // 每秒最多10个请求
          },
          {
            name: 'medium',
            ttl: 60000, // 1分钟
            limit: 100, // 每分钟最多100个请求
          },
          {
            name: 'long',
            ttl: 3600000, // 1小时
            limit: 1000, // 每小时最多1000个请求
          },
        ],
      }),
    }),

    // 缓存模块
    CacheModule.registerAsync({
      isGlobal: true,
      useFactory: () => ({
        ttl: 300, // 5分钟
        max: 1000, // 最多缓存1000个项目
        isGlobal: true,
      }),
    }),

    // 调度模块
    ScheduleModule.forRoot(),

    // 事件发射器模块
    EventEmitterModule.forRoot({
      wildcard: false,
      delimiter: '.',
      newListener: false,
      removeListener: false,
      maxListeners: 10,
      verboseMemoryLeak: false,
      ignoreErrors: false,
    }),

    // 静态文件服务
    ServeStaticModule.forRoot({
      rootPath: join(__dirname, '..', 'public'),
      serveRoot: '/static',
      exclude: ['/api*', '/socket.io*'],
    }),

    // 数据库模块
    DatabaseModule,

    // Redis模块
    RedisModule,

    // 业务模块
    RoomsModule,
    WebsocketModule,
    HealthModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
